import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import { t } from './locale'
import { Ref, nextTick } from 'vue'
import comFunc from './comFunc'
import sessionStoreHelper from './sessionStoreHelper'

declare type ElLoadingInstance = ReturnType<typeof ElLoading.service>

const showLoading = (): ElLoadingInstance => {
  return ElLoading.service({
    lock: true,
    text: t('加载中') + '...',
    spinner: 'el-icon-ElLoading',
    background: 'rgba(128, 128, 128, 0.5)'
  })
}
const closeLoading = (loading: ElLoadingInstance) => {
  if (loading) loading.close()
}

const showSuccessMsg = (msg: string) => {
  ElMessage({
    message: t(msg),
    type: 'success'
  })
}
const showWarningMsg = (msg: string) => {
  ElMessage({
    message: t(msg),
    type: 'warning'
  })
}
const showErrorMsg = (msg: string) => {
  ElMessage.error(t(msg))
}
const showTextMsg = (msg: string) => {
  ElMessage(t(msg))
}
const showConfirmMsg = async (msg: string): Promise<boolean> => {
  let re = await ElMessageBox.confirm(msg, 'Warning', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
    title: '提醒'
  })
    .then(() => true)
    .catch(() => false)
  return re
}
const setPageNavigationStyle = (pn: HTMLElement, total: Ref<number>) => {
  if (!pn) return
  nextTick(() => {
    pn.querySelector('.el-pagination__total')!.innerHTML = `${t('总计')} ${total.value} 笔`
    pn.querySelector('.el-pagination__goto')!.innerHTML = `${t('前往')}`
  })
}

const downloadFile = function (fileUrl: string, filename: string) {
  // 创建隐藏的可下载链接
  const eleLink = document.createElement('a')
  eleLink.download = filename
  eleLink.style.display = 'none'
  // 字符内容转变成地址
  eleLink.href = fileUrl
  eleLink.setAttribute('target', '_blank')
  // 触发点击
  document.body.appendChild(eleLink)
  eleLink.click()
  // 然后移除
  document.body.removeChild(eleLink)
}
function downloadFileByBase64(base64, name) {
  var myBlob = comFunc.dataURLtoBlob(base64)
  var myUrl = URL.createObjectURL(myBlob)
  downloadFile(myUrl, name)
}
export default {
  showLoading,
  closeLoading,
  showErrorMsg,
  showSuccessMsg,
  showTextMsg,
  showWarningMsg,
  showConfirmMsg,
  setPageNavigationStyle,
  downloadFile,
  downloadFileByBase64
}
